package com.rookie.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rookie.common.lang.Result;
import com.rookie.entity.Menu;
import com.rookie.common.dto.MenuDto;
import com.rookie.entity.RoleMenu;
import com.rookie.entity.User;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 前端控制器
 */
@RestController
@RequestMapping("/rookie/menu")
public class MenuController extends BaseController {

    /**
     * 查询当前用户的菜单和权限信息
     */
    @GetMapping("nav")
    public Result nav(Principal principal) {
        User user = userService.getUserByUsername(principal.getName());
        // 权限信息
        String authorityInfo = userService.getUserAuthorityInfo(user.getId());
        String[] authorityArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");
        // 导航栏信息
        List<MenuDto> nav = menuService.getCurrentUserNav();
        Map<Object, Object> map = MapUtil.builder().put("nav", nav).put("authoritys", authorityArray).map();
        return Result.success(map);
    }

    /**
     * 新增
     */
    @PostMapping("save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result save(@Validated @RequestBody Menu menu) {
        menu.setCreateTime(LocalDateTime.now());
        menuService.save(menu);
        return Result.success(menu);
    }

    /**
     * 查询树形列表
     */
    @GetMapping("list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result list() {
        List<Menu> menuList = menuService.treeMenu();
        return Result.success(menuList);
    }

    /**
     * 根据id查询菜单信息
     */
    @GetMapping("getInfoById/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result getInfoById(@PathVariable Long id) {
        Menu menu = menuService.getById(id);
        return Result.success(menu);
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result update(@Validated @RequestBody Menu menu) {
        menu.setUpdateTime(LocalDateTime.now());
        menuService.updateById(menu);
        // 清除redis中的菜单权限
        userService.clearRedisAuthorityByMenu(menu.getId());
        return Result.success(menu);
    }

    /**
     * 删除
     */
    @PostMapping("delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result delete(@PathVariable Long id) {
        long count = menuService.count(new LambdaQueryWrapper<Menu>().eq(Menu::getParentId, id));
        if (count > 0) return Result.fail("请先删除子菜单");
        // 删除菜单
        menuService.removeById(id);
        // 删除角色菜单关联表
        roleMenuService.remove(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getMenuId, id));
        // 清除Redis中的菜单权限
        userService.clearRedisAuthorityByMenu(id);
        return Result.success("");
    }

}
